<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen" 
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"               
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
      
      </template>
      <template v-if="operateType == 'edit'" slot="subjectForm" slot-scope="scope">
        <avue-crud :option="subjectOption" 
               :data="subjectData"
               :table-loading="sbujectLoading" 
               ref="subjectCrud"
               v-model="subjectForm"
               :before-open="subjectBeforeOpen"
               @sortable-change="subjectSaveOrUpdate"
               @row-del="subjectRowDel"
               @row-update="subjectRowUpdate"
               @row-save="subjectRowSave"
               @refresh-change="subjectRefreshChange"
               @sort-change="sortChange"
               @row-dblclick="subjectHandleRowDBLClick"               
               @on-load="subjectOnLoad">
            <template slot="subjectContent" slot-scope="scope">
              <div v-for="(item,index) in JSON.parse(scope.row.subjectContent)" :key="index">
                <span style="font-weight:normal;color:#777777"></span> {{item.label}}、{{item.value}} 
                <span style="color:blue"> {{item.gotoSubject?'【跳转】':''}}</span>
              </div>
            </template>
        </avue-crud>
      </template>
      <template slot-scope="scope" slot="menuForm">
        <div  style="text-align:right; float:right">
          <el-button type="text"  v-if="operateType == 'edit'"   icon="el-icon-time" style="font-weight:normal;" size="large" @click.stop="getHistoryRecord">修改历史</el-button>
        </div> 
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.biz_question_template_batch_delete"
                   @click.stop="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button v-if="permission.biz_question_template_download" type="default" @click.stop="openBatchAddDialog"  title="上传" icon="el-icon-upload" circle size="small"></el-button>
        <el-button v-if="permission.biz_question_template_download" type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-document-copy"
                   v-if="permission.database_delete"
                   @click="openCopyDialog(scope.row)">复制
        </el-button>
        <el-button type="text"
                   size="small"
                   icon="el-icon-view"
                   v-if="permission.database_delete"
                   @click="viewQuestion(scope.row)">预览
        </el-button>
        <el-button type="text"
                   size="small"
                   icon="el-icon-s-promotion"
                   v-if="permission.database_delete"
                   @click="sendQuestionNow(scope.row)">下发
        </el-button>
      </template>
    </avue-crud>
    <!-- 
      加载已发送批次
     -->
    <el-dialog title="选择下发批次" width="60%"  :close-on-click-modal='false' @close="batchDailog = false" :visible.sync="batchDialog">
        
        <div style="padding:0 15px 20px 15px">
          <el-button type="primary" size="small" @click="createNowBatch">新建下发批次</el-button>
          <el-table
          :data="templateSendData"
          border
          style="width: 100%">
          <el-table-column
            prop="projectName"
            label="所属项目" >
          </el-table-column>
          <el-table-column
            prop="questionnaireTitle"
            label="标题" >
          </el-table-column>
          <el-table-column
            prop="sendDatetime"
            label="下发日期" >
          </el-table-column>
          <el-table-column
            prop="batchNo"
            label="批次号" >
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="120">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="sendByBatch(scope.$index, scope.row)"
                type="text"
                size="small">
                选择下发
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!-- 
      选择用户发送
     -->
    <el-dialog title="下发问卷" width="60%"  :close-on-click-modal='false' @close="sendUserDialog = false" :visible.sync="sendUserDialog">
        
        <el-transfer v-model="choseUserValue" 
          filterable
          :titles="['所有机构', '已下发机构']"
          :button-texts="['移除', '添加 ']"
          @change="roleChanged"
          :data="allUserData">
        </el-transfer>
        <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="sendNow($event)" >确定</el-button>
        <el-button size="small" @click="sendUserDialog = false">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 
      复制对话框
     -->
    <el-dialog title="确定要复制？" width='40%' :close-on-click-modal='false' :visible.sync="copyDialog">
      <el-select v-model="projectValue" placeholder="请选择复制到的项目" style="width:100%">
        <el-option
          v-for="item in projectListTmp"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleCopy()" >复制</el-button>
        <el-button size="small" @click="copyDialog = false">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 
      预览对话框
     -->
    <el-dialog title="问卷预览" :modal='false' top="1vh" center width='80%' :close-on-click-modal='false' :visible.sync="previewDialog">
      <preview-question-sheet :templateId="templateId">
      </preview-question-sheet>
    </el-dialog>
    <!-- 批量导入数据 -->
    <upload-excel ref="uploadExcel" :actionUrl='actionUrl' :batchAddDialog='batchAddDialog'></upload-excel>
    <!-- 历史记录 -->
    <update-history ref="historyRecord"></update-history>
  </basic-container>
</template>

<script>
import {queryBizQuestionSendRecordListPage} from '@/api/biz/question/bizQuestionSendRecordApi';

import {queryBizQuestionSendListListPage} from '@/api/biz/question/bizQuestionSendListApi';
import {querySysCustomUserInfoListPage} from '@/api/system/sysCustomUserInfoApi';
import {sendQuestionNow,exportBizQuestionTemplateExcel,saveOrUpdateBizQuestionTemplate,saveOrUpdateBizQuestionTemplateList,saveBizQuestionTemplate,saveBizQuestionTemplateList,deleteBizQuestionTemplate,queryBizQuestionTemplate,queryBizQuestionTemplateListPage,updateBizQuestionTemplate,deleteBizQuestionTemplateList} from '@/api/biz/question/bizQuestionTemplateApi';
import {saveOrUpdateBizQuestionSubjectConfigList,saveBizQuestionSubjectConfig,saveBizQuestionSubjectConfigList,deleteBizQuestionSubjectConfig,queryBizQuestionSubjectConfig,queryBizQuestionSubjectConfigListPage,updateBizQuestionSubjectConfig,deleteBizQuestionSubjectConfigList} from '@/api/biz/question/bizQuestionSubjectConfigApi';

import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import {getToken} from '@/util/auth'
import previewQuestionSheet from '@/views/biz/question/previewQuestionSheet.vue';
export default {
  components: {
    // 项目新增、详情页
    previewQuestionSheet
  },
  data() {
    return {
      //批量导入
      batchAddDialog: false,
      actionUrl: '/biz/question/bizQuestionTemplate/uploadExcel',

      //角色对话框
      fullscreenLoading: false,
      sendUserDialog: false,
      allUserData: [],
      choseUserValue: [],
      oldChoseUserValue: [],
      currentBatchNo:'',
      templateSendData:[],
      batchDialog: false,

      //预览对话框
      previewDialog: false,
      templateId: '',
      //文件选择器的打开方式 add新增、edit修改、view 查看
      openType: 'edit',
      // 当前打开form对话框操作类型 
      operateType: 'add',
      // 项目临时列表
      projectListTmp: [],
      //如果做流程表单 请将次开关设置为true，否则设置为false
      isFlow: true,
      flowArea: {},
      importDataArea: '',
      copyDialog: false,
      projectValue: '',
      copyRow: {},
      form: {},
      currentRow: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      firstLoad: true,
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 125,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: false,
        delBtn: false,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 250,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: '项目名称',
            prop: 'projectNo', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 50,
            overHidden: true,
            rules: [{
              message: '请输入项目名称',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '问卷类型',
            prop: 'questionnaireType', 
            type: 'select', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            rules: [{
              message: '请输入问卷类型',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '问卷标题',
            prop: 'questionnaireTitle', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: false,
            maxlength: 200,
            overHidden: true,
            rules: [{
              message: '请输入问卷标题',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 200,
              message: '内容长度不能超过200字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '问卷公告',
            prop: 'questionnaireNotice', 
            type: 'ueditor',
            component: 'avue-ueditor',
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: true,
            maxlength: 500,
            minRows:3,
            maxRows:3, 
            overHidden: true,
            options: {
              action: '/file/upload',
              props: {
                res: '',
                url: 'filePath',
              },
            }
          },
          
          {
            label: '生成频率',
            prop: 'generateFrequency', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 8,
            sortable: false,
            hide: false,
            maxlength: 10,
            overHidden: true,
            value: '1-N',
            rules: [{
              message: '请输入生成频率',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 10,
              message: '内容长度不能超过10字符',
              trigger: 'blur'
            }],
            dicData:[],
            change: ({value,column}) => {
              if(value == '1-N'){
                this.findObject(this.option.column, 'generateMonth').display = false;  
                this.findObject(this.option.column, 'generateDay').display = false;  
                this.findObject(this.option.column, 'generateDatetime').display = false;  
              }
              else if(value == '1-D'){
                this.findObject(this.option.column, 'generateMonth').display = false;  
                this.findObject(this.option.column, 'generateDay').display = false;  
                this.findObject(this.option.column, 'generateDatetime').display = true;  
              }
              else if(value == '1-W'){
                this.findObject(this.option.column, 'generateMonth').display = false;  
                this.findObject(this.option.column, 'generateDay').display = true;  
                this.findObject(this.option.column, 'generateDatetime').display = true;  
              }
              else if(value == '1-M'){
                this.findObject(this.option.column, 'generateMonth').display = false;  
                this.findObject(this.option.column, 'generateDay').display = true;  
                this.findObject(this.option.column, 'generateDatetime').display = true;  
              }
              else if(value == '1-Y'){
                this.findObject(this.option.column, 'generateMonth').display = true;  
                this.findObject(this.option.column, 'generateDay').display = true;  
                this.findObject(this.option.column, 'generateDatetime').display = true;  
              }
            }
          },
          {
            label: '生成月',
            prop: 'generateMonth', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 8,
            sortable: false,
            hide: false,
            maxlength: 10,
            overHidden: true,
            value: '01',
            display: true,
            rules: [{
              message: '请输入生成日',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 10,
              message: '内容长度不能超过10字符',
              trigger: 'blur'
            }],
            dicData:[
              {label: '01',value:'01'},
              {label: '02',value:'02'},
              {label: '03',value:'03'},
              {label: '04',value:'04'},
              {label: '05',value:'05'},
              {label: '06',value:'06'},
              {label: '07',value:'07'},
              {label: '08',value:'08'},
              {label: '09',value:'09'},
              {label: '10',value:'10'},
              {label: '11',value:'11'},
              {label: '12',value:'12'}
            ],
          },
          {
            label: '生成日',
            prop: 'generateDay', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 8,
            sortable: false,
            hide: false,
            maxlength: 10,
            overHidden: true,
            value: '01',
            display: true,
            rules: [{
              message: '请输入生成日',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 10,
              message: '内容长度不能超过10字符',
              trigger: 'blur'
            }],
            dicData:[
              {label: '01',value:'01'},
              {label: '02',value:'02'},
              {label: '03',value:'03'},
              {label: '04',value:'04'},
              {label: '05',value:'05'},
              {label: '06',value:'06'},
              {label: '07',value:'07'},
              {label: '08',value:'08'},
              {label: '09',value:'09'},
              {label: '10',value:'10'},
              {label: '11',value:'11'},
              {label: '12',value:'12'},
              {label: '13',value:'13'},
              {label: '14',value:'14'},
              {label: '15',value:'15'},
              {label: '16',value:'16'},
              {label: '17',value:'17'},
              {label: '18',value:'18'},
              {label: '19',value:'19'},
              {label: '20',value:'20'},
              {label: '21',value:'21'},
              {label: '22',value:'22'},
              {label: '23',value:'23'},
              {label: '24',value:'24'},
              {label: '25',value:'25'},
              {label: '26',value:'26'},
              {label: '27',value:'27'},
              {label: '28',value:'28'},
              {label: '29',value:'29'},
              {label: '30',value:'30'},
              {label: '31',value:'31'}
            ],
          },
          {
            label: '生成时间点',
            prop: 'generateDatetime', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 8,
            sortable: false,
            hide: false,
            maxlength: 10,
            overHidden: true,
            value: '00:00:00',
            display: true,
            rules: [{
              message: '请输入生成时间点',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 10,
              message: '内容长度不能超过10字符',
              trigger: 'blur'
            }],
            dicData:[
              {label: '00:00:00',value:'00:00:00'},
              {label: '01:00:00',value:'01:00:00'},
              {label: '02:00:00',value:'02:00:00'},
              {label: '03:00:00',value:'03:00:00'},
              {label: '04:00:00',value:'04:00:00'},
              {label: '05:00:00',value:'05:00:00'},
              {label: '06:00:00',value:'06:00:00'},
              {label: '07:00:00',value:'07:00:00'},
              {label: '08:00:00',value:'08:00:00'},
              {label: '09:00:00',value:'09:00:00'},
              {label: '10:00:00',value:'10:00:00'},
              {label: '11:00:00',value:'11:00:00'},
              {label: '12:00:00',value:'12:00:00'},
              {label: '13:00:00',value:'13:00:00'},
              {label: '14:00:00',value:'14:00:00'},
              {label: '15:00:00',value:'15:00:00'},
              {label: '16:00:00',value:'16:00:00'},
              {label: '17:00:00',value:'17:00:00'},
              {label: '18:00:00',value:'18:00:00'},
              {label: '19:00:00',value:'19:00:00'},
              {label: '20:00:00',value:'20:00:00'},
              {label: '21:00:00',value:'21:00:00'},
              {label: '22:00:00',value:'22:00:00'},
              {label: '23:00:00',value:'23:00:00'}
            ],
          },
          {
            label: '截止日期',
            prop: 'validDate', 
            type: 'date', 
            format:'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            value: this.$toolUtil.formatDate(new Date()),
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() + 3600 * 1000 * 24 <= Date.now();
              }
            },
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: false,
            maxlength: 20,
            overHidden: true,
            rules: [{
              message: '请输入有效日期',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 20,
              message: '内容长度不能超过20字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            labelWidth:0,
            label: '',
            prop: 'subject',
            span:24,
            hide:true,
            formslot:true,
          }
        ]
      },
      data: [],
      // 题目定义
      subjectForm: {},
      subjectCurrentRow: {},
      subjectLoading: true, 
      subjectOption: {
        columnBtn: false,
        refreshBtn: true,
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 125,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: false,
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        cancelBtn: true,
        cellBtn:false,
        printBtn:false,
        saveBtn: true,
        filterBtn:false,          
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable:true,
        emptyText:'暂无题目',
        addBtnText:'新增题目',
        column: [
          {
            label: '题目标题',
            prop: 'subjectTitle', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: false,
            maxlength: 200,
            width:400,
            overHidden: true, 
            rules: [{
              message: '请输入题目标题',
              required:  true,
              trigger: 'blur'
            }],
          }, 
          {
            label: '题目性质',
            prop: 'subjectProperties', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 6,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            width:80,
            value:'主题目',
            rules: [{
              message: '请选择题目性质',
              required:  true,
              trigger: 'blur'
            }],
            dicData:[
              {label:'主题目',value:'主题目'},
              {label:'跳转题目',value:'跳转题目'},
              {label:'分割内容',value:'分割内容'}
            ],
            change: ({value,column}) => {
              if(value == '分割内容'){
                //this.findObject(this.subjectOption.column[5].children.column, 'gotoSubject').disabled = false;  
                this.findObject(this.subjectOption.column, 'subjectContent').display = false;  
              }
              else{
                if(this.subjectForm.subjectType == '多选' || this.subjectForm.subjectType == '单选' || this.subjectForm.subjectType == '下拉选择'){
                  this.findObject(this.subjectOption.column, 'subjectContent').display = true;  
                }
                else{
                  this.findObject(this.subjectOption.column, 'subjectContent').display = false;   
                }
              }
            }
          },
          {
            label: '题目类型',
            prop: 'subjectType', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 6,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            width:80,
            value:'文本',
            rules: [{
              message: '请输入题目类型',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            dicData:[],
            change: ({value,column}) => {
              if(value == '多选' || value == '单选' || value == '下拉选择'){
                //this.findObject(this.subjectOption.column[5].children.column, 'gotoSubject').disabled = false;  
                this.findObject(this.subjectOption.column, 'subjectContent').display = true;  
              }
              else{
                this.findObject(this.subjectOption.column, 'subjectContent').display = false;   
              }
            }
          },
          
          {
            label: '是否必填',
            prop: 'isRequired', 
            type: 'radio', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 6,
            sortable: false,
            hide: false,
            maxlength: 1,
            overHidden: true,
            width:80,
            value: '1',
            rules: [{
              message: '请输入是否必填',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 1,
              message: '内容长度不能超过1字符',
              trigger: 'blur'
            }],
            dicData:[
              {
                label: '是',
                value: '1'
              },
              {
                label: '否',
                value: '2'
              }
            ],
          },
          {
            label: '题目分值',
            prop: 'score', 
            type: 'number', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 6,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            width:80,
            maxRows: 100,
            minRows:0,
            value: 0,
            disabled: false,
            rules: [{
              message: '请输入题目分值',
              required:  false,
              trigger: 'blur'
            }],
            dicData:[],
          },
          {
            label: '题目选项',
            prop: 'subjectContent', 
            type: 'input', 
            width:300,
            slot: true, 
            display: false
          },
          {
            label: '题目选项',
            prop: 'subjectContent', 
            type: 'dynamic', 
            span:24,
            slot: true,
            hide: false,
            display: false,
            children: {
              align: 'center',
              headerAlign: 'center', 
              column: [
                {
                  width: 200,
                  label: '选项标签',
                  prop: 'label',
                  type: 'input',
                  rules:[{
                    required:  true,
                    message: '请输入内容',
                  }],
                }, 
                {
                  label: '选项内容',
                  prop: 'value',
                  type: 'input',
                  rules:[{
                    required:  true,
                    message: '请输入内容',
                  }],
                },
                {
                  label: '跳转到题目',
                  prop: 'gotoSubject',
                  type: 'select',
                  filterable: true,
                  rules:[{
                    required:  false,
                    message: '请选择跳转到题目',
                  }],
                  dicData:[]
                }
              ]
            }
          },
          
          {
            label: '题目答案',
            prop: 'subjectAnswer', 
            type: 'textarea', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 24,
            sortable: false,
            hide: false,
            maxlength: 500,
            width:200,
            maxRows:2,
            minRows:2,
            overHidden: true,
            rules: [{
              message: '请输入题目答案',
              required:  false,
              trigger: 'blur'
            },
            {
              max: 500,
              message: '内容长度不能超过500字符',
              trigger: 'blur'
            }],
            dicData:[],
          },
        ]
      },
      subjectData: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10
      },
      subjectReqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {},
      subjectSingleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','orgTree','genOrgTree','userInfo','permission','projectList']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.biz_question_template_add, false),
        viewBtn: this.vaildData(this.permission.biz_question_template_view, false),
        delBtn: this.vaildData(this.permission.biz_question_template_delete, false),
        editBtn: this.vaildData(this.permission.biz_question_template_edit, false),
        printBtn: this.vaildData(this.permission.biz_question_template_print, false),
        searchBtn:this.vaildData(this.permission.biz_question_template_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    
    /**
     * 加载列表数据
     */
    onLoad(page) { 
   	  //如果和项目相关，请打开项目ID作为查询条件
      //if(!this.$project.checkChooseProject()){
      //  return false;
      //}
      //this.singleBody.projectId = this.projectInfo.id;
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryBizQuestionTemplateListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.reqParams.singleBody.projectName = row.$projectNo
      let formatUser = {};
      this.commonData = reqCommonMsg(this.reqParams)
      saveBizQuestionTemplate(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) {
      this.$console.log('==row===:',row.questionnaireNotice);
      this.reqParams.singleBody = row;
      this.reqParams.singleBody.projectName = row.$projectNo
      let formatUser = {};
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizQuestionTemplate(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteBizQuestionTemplate(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 加载已下发的批次记录
     */
    sendQuestionNow(row) {
      this.currentRow = row;
      this.loading = true;
      this.reqParams =  {
        singleBody: {
          templateId: row.id
        },
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: {
          order: 'desc',
          prop: 'createDatetime'
        },
        currentPage: 1, 
        pageSize: 999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryBizQuestionSendRecordListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.templateSendData = data.listBody;
        this.loading = false;
        if(this.templateSendData.length == 0){
          this.batchDialog = false;
          this.currentBatchNo = '';
          this.getAllUserList(false);
        }
        else{
          this.batchDialog = true;
        }
       
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 选择批次下发
     */
    sendByBatch(index,row){
      this.currentBatchNo = row.batchNo
      this.getAllUserList(true);
    },
    /**
     * 新建下发批次
     */
    createNowBatch(){
      this.currentBatchNo = '';
      this.getAllUserList(false);
    },
    /**
     * 获取所有下载对象列表
     */
    getAllUserList(loadSend) { 
      this.sendUserDialog = true;
      this.allUserData=[];
      this.choseUserValue=[];
      this.oldChoseUserValue=[];
      //this.loading = true;
      this.reqParams =  {
        singleBody: {
          status: '1'
        },
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: 99999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      querySysCustomUserInfoListPage(this.commonData).then(res => {
        const data = res.data.body.listBody;
        data.forEach(element => {
          this.allUserData.push({
            key: element.userName,
            label: element.orgName,
            disabled: (element.status == '0') ? true: false
          });
        });
        if(loadSend){
          this.loadSendedUsers();
        }
      }, error => {
        this.loading = false; 
      });

    },
    /**
     * 加载已发送用户
     */
    loadSendedUsers(){
      //this.loading = true;
      this.singleBody.batchNo = this.currentBatchNo;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: 99999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryBizQuestionSendListListPage(this.commonData).then(res => {
        this.choseUserValue=[];
        this.oldChoseUserValue=[];
        res.data.body.listBody.forEach(element => {
          this.choseUserValue.push(element.fillInUserName);
          this.oldChoseUserValue.push(element.fillInUserName);
          this.allUserData.forEach(userElement => {
            if(element.fillInUserName == userElement.key){
              userElement.disabled = true;
              userElement.label = userElement.label+'【已下发】';
            }
          });
        });
        this.loading = false; 
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 确定下发
     */
    sendNow(){
      //只发送新增加的用户列表,已发送的不再发送
      let sendUserList = [];
      this.choseUserValue.forEach(element => {
        let inOldUserList = false;
        this.oldChoseUserValue.forEach(oldElement => {
          if(element == oldElement){
            inOldUserList = true;
          }
        });
        if(!inOldUserList){
          sendUserList.push(element);
        }
      });
      if(sendUserList.length == 0){
        this.$message({
          type: 'warning',
          message: '没有新增任何下发机构!'
        });
        return false;
      }      
      //
      this.$confirm('确定要下发问卷?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody =  this.currentRow;
          this.reqParams.singleBody.sendUserList = sendUserList
          this.reqParams.singleBody.batchNo = this.currentBatchNo
          this.commonData = reqCommonMsg(this.reqParams);
          return sendQuestionNow(this.commonData);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '下发成功!'
          });
          this.reqParams.singleBody={},
          this.sendUserDialog = false;
        }).catch(() => {});
    },
    /**
     * 预览问卷
     */
    viewQuestion(item){
      this.previewDialog = true;
      this.templateId = item.id;
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.biz_question_template_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
      this.$refs.uploadExcel.openUploadDialog();
    },
    /**
     * 批量导入
     */
    handleImport() {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              projectNo:field[0].trim(),
              projectName:field[1].trim(),
              questionnaireType:field[2].trim(),
              questionnaireTitle:field[3].trim(),
              questionnaireNotice:field[4].trim(),
              mobileNo:field[5].trim(),
              generateFrequency:field[6].trim(),
              validDate:field[7].trim(),
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveBizQuestionTemplateList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          this.$console.log(error);
          loading.close();
        });      
      }
      else{
        this.loading=false;
        this.$message({
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 批量导入Excel
     */
    handleImportExcel(){
      this.$refs.batchAddUpload.submit();
    },
    /**
     * 导入成功
     */
    handleSuccess(response, file, fileList){
      this.$console.log('response:',response);
      this.$console.log('fileList:',fileList);
      if(response.head.respCode == 'S0000'){
        this.$message({
          type: 'success',
          message: '处理成功！'
        });
      }
      else{
        file.status = 'error';
        this.errorMsg = '';
        for(var key in response.head.respMsg){
          this.errorMsg += '<div>'+key+':'+'<span style="font-size:12px;color:#ff0000">'+response.head.respMsg[key]+'</span></div>'
        }
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteBizQuestionTemplateList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 打开复制对话框
     */
    openCopyDialog(row){
      this.copyRow =  row;
      this.copyDialog =  true;
    },
    /**
     * 拷贝记录
     */
    handleCopy(){
      //this.$console.log('projectValue===',this.projectValue);
      this.copyDialog = false;
      let projectName = '';
      //获取项目名称
      this.projectListTmp.forEach(element => {
        //this.$console.log('element.value===',element.value);
        if(element.value == this.projectValue){
          projectName = element.label
        }
      });
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        this.form =  this.copyRow;
        let id = this.copyRow.id;
        let copyValue= this.form  ;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.questionnaireTitle='拷贝 - '+ copyValue.questionnaireTitle; 
        this.reqParams.singleBody = copyValue;
        this.reqParams.singleBody.projectNo = this.projectValue;
        this.reqParams.singleBody.projectName = projectName;
        this.commonData = reqCommonMsg(this.reqParams)
        saveBizQuestionTemplate(this.commonData).then((res) => {
          this.singleBody={};
          const data = res.data.body;
          this.form  = data.singleBody;
          this.copyRow.id = id;
          this.onLoad(this.page);
          this.loading=false;
          this.copySubject();
        }, error => {
          this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});
    },
    /**
     * 开始复制题目
     */
    async copySubject(){
      let idTmp = this.form.id;
      this.form.id = this.copyRow.id;
      await this.subjectOnLoad(this.page);
      this.subjectData.forEach(element => {
        element.id = '';
        element.projectNo = this.form.projectNo;
        element.projectName = this.form.projectName;
        element.questionnaireTemplateId = idTmp;
        element.questionnaireTemplateTitle = this.form.questionnaireTitle;
      });
      
      this.reqParams.listBody = this.subjectData;
      this.commonData = reqCommonMsg(this.reqParams)
      saveBizQuestionSubjectConfigList(this.commonData).then((res) => {
        this.singleBody={};
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.loading=false;
      }, error => {
        this.$console.log(error);
        this.loading=false;
      });
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.operateType = 'edit';
        this.reqParams =  {
          singleBody: {
            id:this.form.id
          }
        }
        let commonData = reqCommonMsg(this.reqParams)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        queryBizQuestionTemplate(commonData).then(res => {
          this.form = res.data.body.singleBody;
          loading.close();
          done();
        }, error => {
          this.$console.log(error);
          loading.close();
          done();
        });
      }
      if (['add'].includes(type)) {
        this.operateType = 'add';
        done();
      }
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  

    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportBizQuestionTemplateExcel(this.commonData);
    },

    ////========题目表控制开始===========
    /**
     * 加载列表数据
     */
    async subjectOnLoad(page) {
      this.subjectLoading = true;
      this.subjectSingleBody = {
        questionnaireTemplateId: this.form.id
      }
      this.subjectReqParams =  {
        singleBody: this.subjectSingleBody,
        listBody: [{}],
        currentPage: 1, 
        orderRule:{
          prop: 'showSeq',
          order: 'ascending' 
        },
        pageSize: 99999
      }
      this.commonData = reqCommonMsg(this.subjectReqParams)
      await queryBizQuestionSubjectConfigListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.subjectData = data.listBody;
        
        this.subjectLoading = false;
      }, error => {
        this.subjectLoading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    subjectRowSave(row, done, loading) {
      this.subjectReqParams.singleBody = row;
      this.subjectReqParams.singleBody.showSeq = this.subjectData.length + 1;
      this.subjectReqParams.singleBody.projectNo = this.form.projectNo;
      this.subjectReqParams.singleBody.projectName = this.form.projectName;
      this.subjectReqParams.singleBody.questionnaireTemplateId = this.form.id;
      this.subjectReqParams.singleBody.questionnaireTemplateTitle = this.form.questionnaireTitle;
      this.commonData = reqCommonMsg(this.subjectReqParams)
      saveBizQuestionSubjectConfig(this.commonData).then(() => {
        done();
        this.subjectSingleBody={};
        this.subjectOnLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    subjectRowUpdate(row, index, done, loading) {
      this.subjectReqParams.singleBody = row;
      this.subjectReqParams.singleBody.projectNo = this.form.projectNo;
      this.subjectReqParams.singleBody.projectName = this.form.projectName;
      this.subjectReqParams.singleBody.questionnaireTemplateId = this.form.id;
      this.subjectReqParams.singleBody.questionnaireTemplateTitle = this.form.questionnaireTitle;
      this.commonData = reqCommonMsg(this.subjectReqParams)
      updateBizQuestionSubjectConfig(this.commonData).then(() => {
        done();
        this.subjectSingleBody={}
        this.subjectOnLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
        done();
      });
    },
    /**
     * 删除一条记录
     */
    subjectRowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.subjectReqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.subjectReqParams);
          return deleteBizQuestionSubjectConfig(this.commonData);
        })
        .then(() => {
          this.subjectOnLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 刷新事件
     */
    subjectRefreshChange(){
      this.subjectOnLoad(this.page);
    },
    /**
     * 双击打开详细窗口
     */
    subjectHandleRowDBLClick (row, event) {
      this.$refs.subjectCrud.rowView(row,row.$index);
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    subjectBeforeOpen(done, type) {
      this.handleSubjectList();
      if (['edit', 'view'].includes(type)) {
        this.subjectReqParams =  {
          singleBody: {
            id:this.subjectForm.id
          }
        }
        let commonData = reqCommonMsg(this.subjectReqParams)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        queryBizQuestionSubjectConfig(commonData).then(res => {
          this.subjectForm = res.data.body.singleBody;
          this.subjectForm.subjectContent = JSON.parse(this.subjectForm.subjectContent);
          loading.close();
          done();
        }, error => {
          this.$console.log(error);
          loading.close();
          done();
        });
      }
      if (['add'].includes(type)) {
        done();
      }
      
    },

    /**
     * 题目排序
     */
    subjectSaveOrUpdate(){
      // 整理顺序
      this.subjectData.forEach((item, index) => {
        this.subjectData[index].showSeq = index+1;
      }); 
      this.subjectReqParams.listBody = this.subjectData;
      this.commonData = reqCommonMsg(this.subjectReqParams)
      saveOrUpdateBizQuestionSubjectConfigList(this.commonData).then(() => {
        this.subjectOnLoad();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '保存成功!'
        });
      }, error => {
        //this.$console.log(error);
      });
      //this.$console.log('this.columnData = ',JSON.stringify(this.columnData))
    },


    /**
     * 处理节点列表控件
     */
    handleSubjectList(){
      if(this.form.questionnaireType == '问卷'){
        this.findObject(this.subjectOption.column, 'score').disabled = true;
      }
      else{
        this.findObject(this.subjectOption.column, 'score').disabled = false;
      }
      //跳转题目
      let dicData = [];
      this.subjectData.forEach(element => {
        if(element.subjectProperties == '跳转题目'){
          dicData.push(
            {
              label: element.subjectTitle,
              value: element.id
            }
          )
        }
      }); 
  
      if(this.subjectOption.column[6].children){ 
        this.findObject(this.subjectOption.column[6].children.column, 'gotoSubject').dicData = dicData;
      } 
    },
    ////========题目表控制结束===========
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["questionnaireType","generateFrequency","subjectType"]');
      this.findObject(this.option.column, 'questionnaireType').dicData = dicData.questionnaireType;
      this.findObject(this.option.column, 'generateFrequency').dicData = dicData.generateFrequency;
      this.findObject(this.subjectOption.column, 'subjectType').dicData = dicData.subjectType;

      //加载项目列表
      let projectInfo=[{label:'所有项目', value:'9999'}];
      this.projectList.forEach(element => {
        projectInfo.push(
          {
            label: element.projectName,
            value: element.projectNo
          }
        );
      }); 
      this.projectListTmp = projectInfo;
      this.findObject(this.option.column, 'projectNo').dicData = projectInfo;
    },
    
    /**
     * 调用子组件方法查询历史
     */
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id);
      })
    },
  },
  created() {
    //如果和项目相关，请打开
    // if(!this.projectInfo || !this.projectInfo.projectName){
    //   this.$message({
    //     type: 'warning',
    //     message: '请选择一个项目再进入！'
    //   });
    //   this.$router.push({path: '/general/project/generalMyProjectSelector'});
    // }
    //初始化文件上传头信息
    this.$console.log('==this.userInfo==',this.userInfo);
    this.headersParam={
      'Authorization': 'bearer ' + getToken(),
      'UserId': this.userInfo.userId,
      'UserSign':'uploadFile',
      'remote': 'no',
      'userName': this.userInfo.userName,
      'realName': encodeURIComponent(this.userInfo.realName),
      'tenantId': this.userInfo.tenantId 
    }
    this.$console.log('==headersParam==',this.headersParam);
    this.showColumn = this.$getStore({name: this.userInfo.userId+'bizQuestionTemplateColumn'});
    //获取业务字典
    setTimeout(() => {
      this.getBizDict();
    }, 1000);
    
    //加载机构
    let getOrgTreeTimer = setInterval(() => {
      if(this.genOrgTree){
        let orgTree = [];
        this.genOrgTree.forEach(element => {
          if(element.orgType == '1'){
            orgTree.push(element);
          }
        });
        clearInterval(getOrgTreeTimer);
      }
    }, 100);
    
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'bizQuestionTemplateColumn', content: this.showColumn});
      },
      deep: true
    }
  }
};
</script>
<style>
  .w-e-text-container{
      height: 60px !important;
  }
  .w-e-full-screen-editor .w-e-text-container{
    height:calc(100% - 42px) !important;
  }

</style>